<template>
  <div>
    <el-card class="w_100" v-loading="spinning">
      <template #header>
        <header>
          <div class="left">主要农产品数量统计</div>
          <div class="right">
            <el-button @click='handleExportXlsMy' type="primary" size="small">下载</el-button>
            <el-select v-model="queryParam.selectUnitId" clearable size="mini" style="width: 150px;margin-left:10px;"
                       @change='unitIdClick' placeholder="请选择区域"
                       v-hasPermi="['nongjt:user:list']" >
              <el-option v-for="{id,area} of unitList" :key="id" :label="area" :value="id">
              </el-option>
            </el-select>
            <el-select v-model="queryParam.selectYear" size="mini" style="width: 80px;margin-left: 10px;"
                       @change='yearSelect'
                       placeholder="请选择年份">
              <el-option v-for="temp of yearList" :key="temp" :label="temp" :value="temp">
              </el-option>
            </el-select>
            <el-date-picker
              v-model="queryParam.selectYearMonth" value-format="yyyy-MM" style="width: 120px;margin-left: 10px;"
              type="month" size="mini" placeholder="请选择月份">
            </el-date-picker>
          </div>
        </header>
      </template>
      <div id='MainProductCharts' style='height: 300px;width: 100%;'></div>
    </el-card>
  </div>
</template>

<script>
import {echartResizeMixins} from "@/views/certificate/charts/echartResizeMixins";

let echarts = require('echarts')
import {getAction, getActionSimple} from "@/utils/axiosUtils";
import {mapGetters} from "vuex";

export default {
  name: 'MainProductCharts',
  mixins:[echartResizeMixins],
  data() {
    return {
      description:'主要农产品数量统计',
      title:'主要农产品数量统计',
      headStyle: {
        'font-weight': 'bold',
        'color': '#676A6C'
      },
      url:{
        mainProduct:'/certificate/certificate_count/mainProduct',
        exportXlsUrl: '/certificate/certificate_count/exportXlsMainProduct'
      },
      spinning:false,
      //查询参数
      queryParam: {
        //默认年份
        selectYear: new Date().getFullYear(),
        //默认年月
        selectYearMonth: null,
        //选中的单位id
        selectUnitId: null
      },
      //图表相关
      chart: null,
      option: {
        title: {
          text: '',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            interval: 0,
            // rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'item',
          formatter: ' {b} 开具数量:{c}'
        },
        //保存为图片，等其他功能,在右上角
        toolbox: {
          feature: {
            saveAsImage: { show: true }
          }
        },
        series: [{
          data: [],
          type: 'bar',
          showBackground: true,
          label: {
            show: true,
            formatter: '{c}',
            position: 'top',
            color: '#5470c6',
            fontSize: 12
          },
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          },
          itemStyle: {
            color: function (params) {
              //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
              let colorList = ['#73c0de','#ee6666','#91cc75','#c23531',
                '#fc8452', '#61a0a8', '#d48265', '#91c7ae',
                '#749f83', '#5470c6'];
              if (params.dataIndex >= colorList.length) {  //给大于颜色数量的柱体添加循环颜色的判断

                return colorList[params.dataIndex % colorList.length]
              }
              return colorList[params.dataIndex]
            }
          }
        }]
      },
      //总量
      total:0,
    }
  },
  created(){
    this.queryParam.selectUnitId = this.selectUnitId
    setTimeout(() => {
      this.getStatistics({ yearStr: this.queryParam.selectYear + '-01-01' ,unitId:this.queryParam.selectUnitId})
    }, 500);
  },
  methods:{
    initChart() {
      if (!this.chart) {
        const dom = document.querySelector('#MainProductCharts')
        this.chart = echarts.init(dom)
        this.chart.on('click',params=>{
          const {name} = params
          let seriesName = null
          let find = this.unitList.find(t=>t.id === this.queryParam.selectUnitId)
          if (find){
            let {area} = find
            this.area = area
            seriesName = area
          }
          let selectTime = this.queryParam.selectYearMonth
          let dateBegin
          let dateEnd
          if(selectTime){
            selectTime = selectTime.substring(0,7);
            dateBegin = selectTime + '-01'
            dateEnd = selectTime +'-31'
          }else {
            dateBegin = this. queryParam.selectYear + '-01-01'
            dateEnd = this. queryParam.selectYear + '-12-31'
          }
          this.$router.push({ path: 'certificate/certificate?area=' + seriesName +
              '&dateBegin=' + dateBegin + '&dateEnd=' + dateEnd + '&productName=' + name})

        })
      }
      this.chart.setOption(this.option)
    },
    //获取数据
    async getStatistics(param) {
        try {
          try {
            this.spinning = true
            const result = await getActionSimple(this.url.mainProduct, param)
            //设置x轴
            this.option.xAxis.data = result.map(t => t.title)
            //设置y轴
            this.option.series[0].data = result.map(t => t.count)
            //展示统计数量
            this.total = this.option.series[0].data.reduce((pre, cur) => pre + cur, 0)
            // this.option.title.text = this.area + this.title +"("+this.total+")"
            this.option.title.text = this.title + "(" + this.total + ")"
            // console.log(this.option.series[0].data)
            //设置子标题 展示查询的日期
            this.setChartsSubtext(param)

            this.initChart()
          } catch (e) {
            console.log(e)
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.spinning = false
        }
    },
    //年份选择事件
    yearSelect(year) {
      let param = {
        yearStr: year,
        unitId:this.queryParam.selectUnitId
      }
      this.getStatistics(param)
      //清空月份
      this.queryParam.selectYearMonth = null
    },
    //区域选择事件
    unitIdClick(n) {
      if (n) {
        let param = {
          unitId: n,
          yearMonthStr : this.queryParam.selectYearMonth
        }
        if (this.queryParam.selectYear) {
          param.yearStr = this.queryParam.selectYear + '-01-01'
        }
        this.getStatistics(param)
        //设置图标
        const { area } = this.unitList.find(t => t.id === n)
        this.area = area
        // this.setCharts(area)
      }
    },
    //设置图表子标题
    setChartsSubtext(param) {
      //设置子标题 展示查询的日期
      let { yearStr, yearMonthStr } = param
      if (yearMonthStr) {
        this.option.title.subtext = yearMonthStr.substring(0, 7)
      } else if (yearStr) {
        this.option.title.subtext = yearStr.substring(0, 4)
      } else {
        this.option.title.subtext = new Date().getFullYear()
      }
    },
    //导出
    async handleExportXlsMy() {
      this.spinning = true
      try {
        let param = {
          unitId : this.queryParam.selectUnitId,
          yearStr : this.queryParam.selectYear,
          yearMonthStr: this.queryParam.selectYearMonth
        }
        console.log("导出参数",param)
        this.download(this.url.exportXlsUrl, {
          ...param
        }, `主要农产品数量统计.xlsx`)
      }finally {
        this.spinning = false
      }
    },
  },
  computed:{
    ...mapGetters([
      'unitList',
      'selectUnitId',
      'yearList'
    ]),
  },
  watch: {
    //监听可查询的年限列表
    yearList(n) {
      if (n.length > 0) {
        const year = n[0]
        //更新双向绑定的年份
        this.queryParam.selectYear = year

      }
    },
    selectUnitId(n){
      this.queryParam.selectUnitId = n
    },
    //监听年月的选择
    'queryParam.selectYearMonth'(n){
      if (n) {
        //更新一下前面的年份
        this.queryParam.selectYear = n.split("-")[0]
        let param = {
          yearMonthStr:n,
          unitId : this.queryParam.selectUnitId
        }
        this.getStatistics(param)
      } else {
        //如果清空,默认查询最新年份
        this.queryParam.selectYear = this.yearList[0]
        const param = {
          yearStr: this.queryParam.selectYear,
          unitId : this.queryParam.selectUnitId
        }
        this.getStatistics(param)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.w_100{
  width: 100%;
}
header{
  display: flex;
  justify-content: space-between;
  align-content: center;

  .left{
    font-weight: bold;
  }
}
</style>
